package com.example.springboottest.example.netty.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        new EchoServer(9000).start();
    }

    public void start() throws Exception {
        final EchoServerInboundHandler1 serverInHandler1 = new EchoServerInboundHandler1();
        final EchoServerInboundHandler2 serverInHandler2 = new EchoServerInboundHandler2();
        final EchoServerOutboundHandler1 serverOutHandler1 = new EchoServerOutboundHandler1();
        final EchoServerOutboundHandler2 serverOutHandler2 = new EchoServerOutboundHandler2();
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            // 注册两个OutboundHandler，执行顺序为注册顺序的逆序
                            // 注册两个InboundHandler， 执行顺序为注册顺序的顺序
                            ch.pipeline().
                                    addLast(serverOutHandler1).
                                    addLast(serverOutHandler2).
                                    addLast(serverInHandler1).
                                    addLast(serverInHandler2);
                        }
                    });
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
